# Cargar librerías adicionales para visualización
library(quantmod)
## Warning: package 'quantmod' was built under R version 4.5.2
## Cargando paquete requerido: xts
## Warning: package 'xts' was built under R version 4.5.2
## Cargando paquete requerido: zoo
## Warning: package 'zoo' was built under R version 4.5.1
## 
## Adjuntando el paquete: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
## Cargando paquete requerido: TTR
## Warning: package 'TTR' was built under R version 4.5.2
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
library(tidyverse)
## Warning: package 'ggplot2' was built under R version 4.5.1
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.5
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   4.0.0     ✔ tibble    3.2.1
## ✔ lubridate 1.9.4     ✔ tidyr     1.3.1
## ✔ purrr     1.0.4
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::first()  masks xts::first()
## ✖ dplyr::lag()    masks stats::lag()
## ✖ dplyr::last()   masks xts::last()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(ggplot2)
library(plotly)
## Warning: package 'plotly' was built under R version 4.5.2
## 
## Adjuntando el paquete: 'plotly'
## 
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## 
## The following object is masked from 'package:stats':
## 
##     filter
## 
## The following object is masked from 'package:graphics':
## 
##     layout
library(scales)
## 
## Adjuntando el paquete: 'scales'
## 
## The following object is masked from 'package:purrr':
## 
##     discard
## 
## The following object is masked from 'package:readr':
## 
##     col_factor
library(gridExtra)
## Warning: package 'gridExtra' was built under R version 4.5.1
## 
## Adjuntando el paquete: 'gridExtra'
## 
## The following object is masked from 'package:dplyr':
## 
##     combine
library(knitr)
library(kableExtra)
## Warning: package 'kableExtra' was built under R version 4.5.1
## 
## Adjuntando el paquete: 'kableExtra'
## 
## The following object is masked from 'package:dplyr':
## 
##     group_rows
library(RColorBrewer)
library(zoo)
library(tseries)
## Warning: package 'tseries' was built under R version 4.5.2
library(forecast)
## Warning: package 'forecast' was built under R version 4.5.2
library(fpp2)
## Warning: package 'fpp2' was built under R version 4.5.2
## ── Attaching packages ────────────────────────────────────────────── fpp2 2.5 ──
## ✔ fma       2.5     ✔ expsmooth 2.3
## Warning: package 'fma' was built under R version 4.5.2
## Warning: package 'expsmooth' was built under R version 4.5.2
## ── Conflicts ───────────────────────────────────────────────── fpp2_conflicts ──
## ✖ scales::discard() masks purrr::discard()
# Definir paleta de colores profesional
color_palette <- c(
  "#1E3A8A",  # Azul oscuro principal
  "#DC2626",  # Rojo para eventos críticos
  "#059669",  # Verde para crecimiento
  "#D97706",  # Ámbar para metales
  "#7C3AED",  # Púrpura para comparaciones
  "#0EA5E9"   # Azul claro para fondos
)
# Cargar librerías necesarias
library(plotly)
library(dplyr)
library(RColorBrewer)

# Datos de composición del ETF
composition_data <- data.frame(
  Metal = c("Oro Físico", "Plata Física", "Paladio Físico", "Platino Físico"),
  Porcentaje = c(61.77, 30.72, 4.26, 3.26),
  Valor_Mercado = c("1B", "702M", "97M", "74M")
)

# Añadir etiquetas detalladas
composition_data <- composition_data %>%
  mutate(
    Etiqueta = paste0(
      "<b>", Metal, "</b><br>",
      Porcentaje, "%<br>",
      "(", Valor_Mercado, ")"
    ),
    # Colores metálicos realistas
    Color = c("goldenrod", "#C0C0C0", "#B8B8B8", "#E5E4E2"),
    # Texto para hover
    HoverText = paste0(
      "<b>", Metal, "</b><br>",
      "Composición: <b>", Porcentaje, "%</b><br>",
      "Valor de mercado: <b>", Valor_Mercado, "</b><br>",
      "Aproximado en cartera:<br>",
      case_when(
        Metal == "Oro Físico" ~ "60-65%",
        Metal == "Plata Física" ~ "25-30%",
        Metal == "Paladio Físico" ~ "3-5%",
        Metal == "Platino Físico" ~ "3-5%"
      )
    )
  )

# Crear donut chart interactivo
donut_interactive <- plot_ly(
  composition_data,
  labels = ~Metal,
  values = ~Porcentaje,
  type = 'pie',
  hole = 0.5,  # Esto crea el efecto donut
  textposition = 'outside',
  textinfo = 'label+percent',
  hoverinfo = 'text',
  text = ~HoverText,
  marker = list(
    colors = ~Color,
    line = list(color = '#FFFFFF', width = 2)
  ),
  # Añadir texto en el centro
  domain = list(x = c(0, 1), y = c(0, 1))
) %>%
  layout(
    title = list(
      text = "<b>Composición del ETF GLTR<br>Aberdeen Standard Physical<br>Precious Metals Basket Shares</b>",
      font = list(
        size = 20,
        color = "#1E3A8A",
        family = "Arial, sans-serif"
      ),
      x = 0.5,
      y = 0.95
    ),
    showlegend = TRUE,
    legend = list(
      orientation = "v",
      x = 1.05,
      y = 0.5,
      font = list(size = 12),
      title = list(
        text = "<b>Metales</b>",
        font = list(size = 14)
      )
    ),
    # Añadir anotación en el centro del donut
    annotations = list(
      list(
        text = "<b>Total AUM</b><br>~$1.9B",
        x = 0.5,
        y = 0.5,
        font = list(
          size = 16,
          color = "#1E3A8A",
          family = "Arial, sans-serif"
        ),
        showarrow = FALSE
      )
    ),
    paper_bgcolor = "#F8F9FA",
    plot_bgcolor = "#F8F9FA",
    margin = list(t = 100, b = 80, l = 20, r = 150)
  )

# Mostrar donut chart
donut_interactive
library(kableExtra)

# Crear tabla comparativa estilo profesional
ficha_tecnica <- data.frame(
  Característica = c(
    "Nombre del ETF",
    "Símbolo/Ticker",
    "Tipo de activo",
    "Activos subyacentes",
    "Composición actual",
    "Activos bajo gestión (AUM)",
    "Expense Ratio",
    "Beta (vs. S&P 500)",
    "Rango 52 semanas",
    "Precio actual (aprox)",
    "Rendimiento 2024",
    "Rendimiento YTD 2025",
    "Volumen promedio diario",
    "Bolsa de cotización",
    "Fecha de lanzamiento"
  ),
  Valor = c(
    "Aberdeen Standard Physical Precious Metals Basket Shares ETF",
    "GLTR",
    "ETF de metales preciosos físicos",
    "Oro, plata, paladio, platino físicos",
    "Oro: 62%, Plata: 31%, Paladio: 4%, Platino: 3%",
    "$1,850 millones USD",
    "0.60%",
    "0.21",
    "$109.20 - $171.85",
    "$168.50",
    "+20.3%",
    "+38.5% (hasta octubre)",
    "150,000 acciones",
    "NYSE Arca",
    "Octubre 2010"
  ),
  Nota = c(
    "Nombre completo del instrumento",
    "Ticker de negociación principal",
    "Clasificación del producto",
    "Metales físicos almacenados en bóvedas",
    "Distribución basada en valores de mercado actuales",
    "Ha crecido 35% en los últimos 12 meses",
    "Competitivo dentro del sector de ETFs de metales",
    "Baja correlación con el mercado accionario",
    "Mínimo histórico: $109.20 (Oct 2024)",
    "Precio de cierre más reciente disponible",
    "Impulsado por rally de metales preciosos",
    "Fuerte desempeño por demanda de activos refugio",
    "Alta liquidez para entrada/salida",
    "Principal exchange para ETFs en EE.UU.",
    "Más de 15 años en el mercado"
  )
)

# Formatear la tabla profesional
ficha_tecnica %>%
  kable(align = "lcl", 
        caption = "Tabla 1. FICHA TÉCNICA DEL ETF GLTR - METALES PRECIOSOS") %>%
  kable_styling(bootstrap_options = c("striped", "hover", "condensed"), 
                full_width = FALSE,
                font_size = 12) %>%
  row_spec(0, background = "#1E3A8A", color = "white", bold = TRUE) %>%
  column_spec(1, bold = TRUE, width = "25%") %>%
  column_spec(2, width = "35%") %>%
  column_spec(3, width = "40%", 
              color = "#666666") %>%
  # Resaltar valores importantes
  column_spec(2,
              color = ifelse(
                grepl("\\+[0-9]", ficha_tecnica$Valor), "#27AE60",  # Verde para rendimientos positivos
                ifelse(
                  grepl("^\\$", ficha_tecnica$Valor), "#3498DB",    # Azul para valores monetarios
                  "black"
                )
              ),
              bold = ifelse(
                grepl("\\+[0-9]|^\\$", ficha_tecnica$Valor),
                TRUE,
                FALSE
              ))
Tabla 1. FICHA TÉCNICA DEL ETF GLTR - METALES PRECIOSOS
Característica Valor Nota
Nombre del ETF Aberdeen Standard Physical Precious Metals Basket Shares ETF Nombre completo del instrumento
Símbolo/Ticker GLTR Ticker de negociación principal
Tipo de activo ETF de metales preciosos físicos Clasificación del producto
Activos subyacentes Oro, plata, paladio, platino físicos Metales físicos almacenados en bóvedas
Composición actual Oro: 62%, Plata: 31%, Paladio: 4%, Platino: 3% Distribución basada en valores de mercado actuales
Activos bajo gestión (AUM) $1,850 millones USD Ha crecido 35% en los últimos 12 meses
Expense Ratio 0.60% Competitivo dentro del sector de ETFs de metales
Beta (vs. S&P 500) 0.21 Baja correlación con el mercado accionario
Rango 52 semanas $109.20 - $171.85 Mínimo histórico: $109.20 (Oct 2024)
Precio actual (aprox) $168.50 Precio de cierre más reciente disponible
Rendimiento 2024 +20.3% Impulsado por rally de metales preciosos
Rendimiento YTD 2025 +38.5% (hasta octubre) Fuerte desempeño por demanda de activos refugio
Volumen promedio diario 150,000 acciones Alta liquidez para entrada/salida
Bolsa de cotización NYSE Arca Principal exchange para ETFs en EE.UU.
Fecha de lanzamiento Octubre 2010 Más de 15 años en el mercado
library(plotly)
library(quantmod)
library(dplyr)
library(zoo)

# Descargar datos
GLTR <- getSymbols("GLTR", src = "yahoo", auto.assign = FALSE, from = "2010-01-01")

# Preparar datos
GLTR_df <- data.frame(
  Fecha = index(GLTR),
  Precio = as.numeric(Cl(GLTR))
)

# Gráfico interactivo
plot_ly(GLTR_df, x = ~Fecha, y = ~Precio, type = "scatter", mode = "lines",
        line = list(color = "#1E3A8A", width = 2),
        hoverinfo = "text",
        text = ~paste("Fecha:", Fecha, "<br>Precio: $", round(Precio, 2))) %>%
  layout(
    title = "<b>ETF GLTR - Serie Histórica (2010-2025)</b>",
    xaxis = list(title = "Fecha", rangeslider = list(visible = TRUE)),
    yaxis = list(title = "Precio (USD)", tickformat = "$,.2f"),
    hovermode = "x unified"
  )
# Plata 2010–2012 (proxy: SLV)
silver_10_12 <- getSymbols("SLV", src = "yahoo", auto.assign = FALSE,
                           from = "2010-01-01", to = "2012-12-31")
silver_10_12_close <- Cl(silver_10_12)

silver_10_12_df <- data.frame(
  fecha  = index(silver_10_12_close),
  precio = as.numeric(silver_10_12_close)
)

g_plata_10_12 <- ggplot(silver_10_12_df, aes(x = fecha, y = precio)) +
  geom_line(color = "gray40", linewidth = 0.8) +
  labs(title = "Precio de la plata 2010–2012 (proxy: SLV)",
       subtitle = "Rally post-crisis y máximos asociados a QE e inflación esperada",
       x = "Fecha", y = "Precio de cierre (USD)") +
  theme_minimal()

g_plata_10_12_int <- ggplotly(g_plata_10_12)
g_plata_10_12_int
library(plotly)
library(quantmod)
library(dplyr)

# Descargar datos si no los tienes
GLTR <- getSymbols("GLTR", src = "yahoo", auto.assign = FALSE, from = "2020-01-01", to = "2020-12-31")

# Preparar datos para 2020
datos_2020 <- data.frame(
  Fecha = index(GLTR),
  Precio = as.numeric(Cl(GLTR))
)

# Crear gráfico interactivo
plot_ly(datos_2020, x = ~Fecha) %>%
  add_trace(y = ~Precio, type = 'scatter', mode = 'lines',
            line = list(color = '#1E3A8A', width = 3),
            name = 'Precio GLTR',
            hoverinfo = 'text',
            text = ~paste('<b>Fecha:</b>', Fecha, '<br><b>Precio:</b> $', round(Precio, 2))) %>%
  
  # Eventos clave
  add_trace(x = as.Date('2020-03-16'), y = ~Precio[Fecha == as.Date('2020-03-16')],
            type = 'scatter', mode = 'markers',
            marker = list(color = '#DC2626', size = 12, symbol = 'circle'),
            name = 'Colapso mercados',
            hoverinfo = 'text',
            text = '<b>16 Mar 2020:</b> Colapso de mercados globales<br>Fed anuncia estímulos de emergencia') %>%
  
  add_trace(x = as.Date('2020-08-07'), y = ~Precio[Fecha == as.Date('2020-08-07')],
            type = 'scatter', mode = 'markers',
            marker = list(color = '#059669', size = 12, symbol = 'diamond'),
            name = 'Récord oro',
            hoverinfo = 'text',
            text = '<b>07 Ago 2020:</b> Oro supera $2,000/oz<br>Rally histórico de metales preciosos') %>%
  
  layout(
    title = list(
      text = '<b>Comportamiento del ETF GLTR durante la Pandemia COVID-19 (2020)</b>',
      font = list(size = 18, color = '#1E3A8A', family = 'Arial'),
      y = 0.98,  # Posición vertical del título
      x = 0.5,   # Posición horizontal centrada
      xanchor = 'center',
      yanchor = 'top'
    ),
    xaxis = list(
      title = '<b>Fecha</b>',
      type = 'date',
      tickformat = '%b %Y',
      rangeslider = list(visible = TRUE)
    ),
    yaxis = list(
      title = '<b>Precio (USD)</b>',
      tickformat = '$.2f',
      gridcolor = 'lightgray'
    ),
    hovermode = 'x unified',
    plot_bgcolor = 'white',
    paper_bgcolor = '#F8F9FA',
    margin = list(t = 120, b = 80, l = 80, r = 40),  # Aumentado margen superior
    showlegend = TRUE,
    legend = list(
      orientation = 'h',
      x = 0.5,
      xanchor = 'center',
      y = -0.2,
      yanchor = 'top'
    )
  )
library(quantmod)
library(ggplot2)
library(plotly)

# Oro 2022 (proxy: GLD)
gold_2022 <- getSymbols("GLD", src = "yahoo", auto.assign = FALSE,
                        from = "2022-01-01", to = "2022-12-31")
gold_2022_close <- Cl(gold_2022)

gold_2022_df <- data.frame(
  fecha  = index(gold_2022_close),
  precio = as.numeric(gold_2022_close)
)

g_oro_2022 <- ggplot(gold_2022_df, aes(x = fecha, y = precio)) +
  geom_line(color = "goldenrod", linewidth = 0.8) +
  labs(title = "Precio del oro en 2022 (proxy: GLD)",
       subtitle = "Volatilidad por guerra en Ucrania e incremento de tasas",
       x = "Fecha", y = "Precio de cierre (USD)") +
  theme_minimal()

g_oro_2022_int <- ggplotly(g_oro_2022)
g_oro_2022_int
library(plotly)
library(quantmod)
library(dplyr)
library(tidyr)

# Descargar datos para 2023 y 2024
GLTR_2023 <- getSymbols("GLTR", src = "yahoo", auto.assign = FALSE, from = "2023-01-01", to = "2023-12-31")
GLTR_2024 <- getSymbols("GLTR", src = "yahoo", auto.assign = FALSE, from = "2024-01-01", to = "2024-12-31")

# Preparar datos para 2023
datos_2023 <- data.frame(
  Fecha = index(GLTR_2023),
  Precio = as.numeric(Cl(GLTR_2023))
) %>%
  mutate(
    Dia = seq_along(Fecha),
    Año = "2023",
    Precio_Norm = Precio / first(Precio) * 100
  )

# Preparar datos para 2024
datos_2024 <- data.frame(
  Fecha = index(GLTR_2024),
  Precio = as.numeric(Cl(GLTR_2024))
) %>%
  mutate(
    Dia = seq_along(Fecha),
    Año = "2024",
    Precio_Norm = Precio / first(Precio) * 100
  )

# Combinar datos
datos_comparativos <- bind_rows(datos_2023, datos_2024)

# Crear gráfico comparativo interactivo
plot_ly(datos_comparativos, x = ~Dia) %>%
  # Línea para 2023
  add_trace(data = subset(datos_comparativos, Año == "2023"),
            y = ~Precio_Norm,
            type = 'scatter',
            mode = 'lines',
            line = list(color = '#DC2626', width = 3),
            name = '2023',
            hoverinfo = 'text',
            text = ~paste('<b>2023 - Día', Dia, '</b><br>',
                          'Fecha:', Fecha, '<br>',
                          'Precio: $', round(Precio, 2), '<br>',
                          'Normalizado:', round(Precio_Norm, 1))) %>%
  
  # Línea para 2024
  add_trace(data = subset(datos_comparativos, Año == "2024"),
            y = ~Precio_Norm,
            type = 'scatter',
            mode = 'lines',
            line = list(color = '#059669', width = 3),
            name = '2024',
            hoverinfo = 'text',
            text = ~paste('<b>2024 - Día', Dia, '</b><br>',
                          'Fecha:', Fecha, '<br>',
                          'Precio: $', round(Precio, 2), '<br>',
                          'Normalizado:', round(Precio_Norm, 1))) %>%
  
  # Línea de referencia en 100
  add_trace(x = c(0, max(datos_comparativos$Dia)),
            y = c(100, 100),
            type = 'scatter',
            mode = 'lines',
            line = list(color = 'gray', width = 1, dash = 'dash'),
            name = 'Línea base (100)',
            showlegend = FALSE) %>%
  
  # Layout
  layout(
    title = list(
      text = '<b>Comparativo de Desempeño: ETF GLTR 2023 vs 2024</b>',
      font = list(size = 22, color = '#1E3A8A')
    ),
    xaxis = list(
      title = '<b>Días de negociación en el año</b>',
      gridcolor = 'lightgray'
    ),
    yaxis = list(
      title = '<b>Precio Normalizado (Inicio = 100)</b>',
      gridcolor = 'lightgray'
    ),
    hovermode = 'x unified',
    plot_bgcolor = 'white',
    paper_bgcolor = '#F8F9FA',
    legend = list(
      orientation = 'h',
      x = 0.5,
      y = -0.15,
      xanchor = 'center'
    ),
    margin = list(t = 80, b = 100, l = 80, r = 40)
  )
library(plotly)
library(quantmod)
library(dplyr)
library(lubridate)

# Descargar datos desde 2023
GLTR_all <- getSymbols("GLTR", src = "yahoo", auto.assign = FALSE, from = "2023-01-01")

# Función para preparar datos por año
preparar_datos_año <- function(año, datos) {
  # Filtrar por año
  datos_año <- datos[year(index(datos)) == año]
  
  if (nrow(datos_año) == 0) return(NULL)
  
  # Crear dataframe
  df <- data.frame(
    Fecha = index(datos_año),
    Precio = as.numeric(Cl(datos_año))
  )
  
  # Calcular día del año y precio normalizado
  df <- df %>%
    mutate(
      Dia_del_año = row_number(),
      Año = as.character(año),
      Precio_Norm = Precio / first(Precio) * 100,
      Retorno = (Precio / first(Precio) - 1) * 100
    )
  
  return(df)
}

# Preparar datos para cada año
datos_2023 <- preparar_datos_año(2023, GLTR_all)
datos_2024 <- preparar_datos_año(2024, GLTR_all)
datos_2025 <- preparar_datos_año(2025, GLTR_all)

# Combinar todos los datos
datos_todos <- bind_rows(datos_2023, datos_2024, datos_2025)

# Crear gráfico interactivo
plot_ly(datos_todos, x = ~Dia_del_año) %>%
  
  # Año 2023
  add_trace(data = subset(datos_todos, Año == "2023"),
            y = ~Precio_Norm,
            type = 'scatter',
            mode = 'lines+markers',
            line = list(color = '#DC2626', width = 2.5),
            marker = list(size = 6, color = '#DC2626'),
            name = '2023',
            hoverinfo = 'text',
            text = ~paste('<b>2023 - Día', Dia_del_año, '</b><br>',
                          'Fecha:', format(Fecha, '%d/%m/%Y'), '<br>',
                          'Precio real: $', round(Precio, 2), '<br>',
                          'Normalizado:', round(Precio_Norm, 1), '<br>',
                          'Retorno:', round(Retorno, 1), '%')) %>%
  
  # Año 2024
  add_trace(data = subset(datos_todos, Año == "2024"),
            y = ~Precio_Norm,
            type = 'scatter',
            mode = 'lines+markers',
            line = list(color = '#059669', width = 2.5),
            marker = list(size = 6, color = '#059669'),
            name = '2024',
            hoverinfo = 'text',
            text = ~paste('<b>2024 - Día', Dia_del_año, '</b><br>',
                          'Fecha:', format(Fecha, '%d/%m/%Y'), '<br>',
                          'Precio real: $', round(Precio, 2), '<br>',
                          'Normalizado:', round(Precio_Norm, 1), '<br>',
                          'Retorno:', round(Retorno, 1), '%')) %>%
  
  # Año 2025 (hasta la fecha disponible)
  add_trace(data = subset(datos_todos, Año == "2025"),
            y = ~Precio_Norm,
            type = 'scatter',
            mode = 'lines+markers',
            line = list(color = '#1E3A8A', width = 2.5),
            marker = list(size = 6, color = '#1E3A8A'),
            name = '2025 (hasta fecha)',
            hoverinfo = 'text',
            text = ~paste('<b>2025 - Día', Dia_del_año, '</b><br>',
                          'Fecha:', format(Fecha, '%d/%m/%Y'), '<br>',
                          'Precio real: $', round(Precio, 2), '<br>',
                          'Normalizado:', round(Precio_Norm, 1), '<br>',
                          'Retorno:', round(Retorno, 1), '%')) %>%
  
  # Línea de referencia en 100
  add_trace(x = c(0, max(datos_todos$Dia_del_año, na.rm = TRUE)),
            y = c(100, 100),
            type = 'scatter',
            mode = 'lines',
            line = list(color = 'gray', width = 1, dash = 'dash'),
            name = 'Línea base (100)',
            showlegend = FALSE,
            hoverinfo = 'skip') %>%
  
  # Layout
  layout(
    title = list(
      text = '<b>Comparativo de Desempeño Anual - ETF GLTR</b><br><span style="font-size:14px">Cada año normalizado a 100 en su primer día de negociación</span>',
      font = list(size = 22, color = '#1E3A8A')
    ),
    xaxis = list(
      title = '<b>Día del año de negociación</b>',
      gridcolor = 'lightgray'
    ),
    yaxis = list(
      title = '<b>Índice Normalizado (Inicio = 100)</b>',
      gridcolor = 'lightgray'
    ),
    hovermode = 'x unified',
    plot_bgcolor = 'white',
    paper_bgcolor = '#F8F9FA',
    legend = list(
      orientation = 'h',
      x = 0.5,
      y = -0.15,
      xanchor = 'center',
      bgcolor = 'rgba(255,255,255,0.8)'
    ),
    margin = list(t = 100, b = 100, l = 80, r = 40),
    
    # Anotaciones con rendimiento final de cada año
    annotations = list(
      list(
        x = max(datos_2023$Dia_del_año, na.rm = TRUE),
        y = tail(datos_2023$Precio_Norm, 1),
        text = paste('2023:', round(tail(datos_2023$Retorno, 1), 1), '%'),
        showarrow = FALSE,
        font = list(size = 12, color = '#DC2626'),
        xanchor = 'left',
        xshift = 10
      ),
      list(
        x = max(datos_2024$Dia_del_año, na.rm = TRUE),
        y = tail(datos_2024$Precio_Norm, 1),
        text = paste('2024:', round(tail(datos_2024$Retorno, 1), 1), '%'),
        showarrow = FALSE,
        font = list(size = 12, color = '#059669'),
        xanchor = 'left',
        xshift = 10
      ),
      list(
        x = max(datos_2025$Dia_del_año, na.rm = TRUE),
        y = tail(datos_2025$Precio_Norm, 1),
        text = paste('2025:', round(tail(datos_2025$Retorno, 1), 1), '%'),
        showarrow = FALSE,
        font = list(size = 12, color = '#1E3A8A'),
        xanchor = 'left',
        xshift = 10
      )
    )
  )
library(kableExtra)

# Crear tabla de síntesis histórica
sintesis_historica <- data.frame(
  Período = c(
    "2010–2012",
    "2013–2015", 
    "2016–2019",
    "2020",
    "2021",
    "2022",
    "2023",
    "2024–2025"
  ),
  Comportamiento = c(
    "Rally alcista",
    "Corrección",
    "Laterización volátil",
    "Rally extremo",
    "Corrección",
    "Volatilidad extrema",
    "Recuperación táctica",
    "Rally estructural"
  ),
  Factores_clave = c(
    "Estímulos post-2008, temor inflación, búsqueda refugio",
    "Tapering Fed, fortaleza dólar, normalización monetaria",
    "Incertidumbre política (Brexit, Trump, guerra comercial), tasas moderadas",
    "Pandemia COVID, pánico financiero, QE infinito, máximos oro",
    "Recuperación económica, rotación a cíclicos, normalización de tasas",
    "Invasión Ucrania (alcista) vs. endurecimiento Fed (bajista) → plano",
    "Crisis bancaria puntual, demanda refugio momentánea, luego normalización",
    "Deuda pública ↑, tasas reales esperadas ↓, incertidumbre geopolítica, máximos históricos"
  )
)

# Crear tabla profesional
sintesis_historica %>%
  kable(
    align = "lll",
    col.names = c("PERÍODO", "COMPORTAMIENTO", "FACTORES CLAVE"),
    caption = "<center><h3 style='color: #1E3A8A;'>Tabla 2. SÍNTESIS HISTÓRICA - TRAYECTORIA DEL ETF GLTR (2010-2025)</h3></center>",
    escape = FALSE
  ) %>%
  kable_styling(
    bootstrap_options = c("striped", "hover", "condensed"),
    full_width = FALSE,
    position = "center",
    font_size = 13,
    fixed_thead = TRUE
  ) %>%
  row_spec(
    0,
    background = "#1E3A8A",
    color = "white",
    bold = TRUE,
    align = "center",
    extra_css = "border-bottom: 2px solid #FFFFFF;"
  ) %>%
  column_spec(
    1,
    bold = TRUE,
    width = "15%",
    background = "#F8FAFC",
    extra_css = "border-right: 1px solid #E5E7EB;"
  ) %>%
  column_spec(
    2,
    width = "20%",
    background = "#FFFFFF",
    extra_css = "border-right: 1px solid #E5E7EB;"
  ) %>%
  column_spec(
    3,
    width = "65%",
    background = "#FFFFFF"
  ) %>%
  # Añadir notas al pie
  footnote(
    general = "Fuente: Análisis histórico basado en datos de Yahoo Finance, Bloomberg y Aberdeen Standard Investments",
    general_title = "Nota:",
    footnote_as_chunk = TRUE,
    title_format = c("italic", "bold")
  )

Tabla 2. SÍNTESIS HISTÓRICA - TRAYECTORIA DEL ETF GLTR (2010-2025)

PERÍODO COMPORTAMIENTO FACTORES CLAVE
2010–2012 Rally alcista Estímulos post-2008, temor inflación, búsqueda refugio
2013–2015 Corrección Tapering Fed, fortaleza dólar, normalización monetaria
2016–2019 Laterización volátil Incertidumbre política (Brexit, Trump, guerra comercial), tasas moderadas
2020 Rally extremo Pandemia COVID, pánico financiero, QE infinito, máximos oro
2021 Corrección Recuperación económica, rotación a cíclicos, normalización de tasas
2022 Volatilidad extrema Invasión Ucrania (alcista) vs. endurecimiento Fed (bajista) → plano
2023 Recuperación táctica Crisis bancaria puntual, demanda refugio momentánea, luego normalización
2024–2025 Rally estructural Deuda pública ↑, tasas reales esperadas ↓, incertidumbre geopolítica, máximos históricos
Nota: Fuente: Análisis histórico basado en datos de Yahoo Finance, Bloomberg y Aberdeen Standard Investments